package com.zeng.sys.authmd.restfulmodule.controller;

import com.zeng.nicecommon.util.ResponseUtil;
import com.zeng.nicecore.validation.ValidGroup;
import com.zeng.sys.authmd.apimodule.service.PermissionService;
import com.zeng.sys.authmd.apimodule.service.com.zeng.sys.authmd.apimodule.constant.PermissionType;
import com.zeng.sys.authmd.apimodule.vo.PermissionVo;
import com.zeng.sys.authmd.apimodule.vo.UserVo;
import com.zeng.sys.authmd.restfulmodule.util.TokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Optional;

@RequestMapping("/menu")
@RestController
@Slf4j
public class MenuController {

    @Autowired
    PermissionService permissionService;

    @RequestMapping("add")
    public Object add(@Validated({ValidGroup.add.class}) PermissionVo permissionVo) {
        log.debug("正在插入菜单资源[{}]", permissionVo);

        permissionVo.setType(PermissionType.MENU);
        PermissionVo insertPermission = permissionService.addOne(permissionVo);

        return ResponseUtil.success("成功响应插入").addData("permission", insertPermission);
    }

    @RequestMapping("list")
    public Object list(HttpServletRequest request) {
        UserVo userByToken = TokenUtil.getUserByToken(request);
        if (userByToken == null) {
            return ResponseUtil.noAuthority("请登录账号");
        }

        String userAccount = Optional.ofNullable(userByToken).orElse(new UserVo()).getUserAccount();
        if ("admin".equals(userAccount)) {
            return ResponseUtil.success("操作成功").addData("menus", permissionService.listAllMenu());
        }
        return ResponseUtil.success("操作成功").addData("menus", permissionService.listAllMenu(userByToken));
//        return ResponseUtil.success("操作成功").addData("menus", permissionService.listAllMenu());
    }

    @RequestMapping("update")
    public Object update(PermissionVo permissionVo) {
        return ResponseUtil.success("操作成功,更行记录数量:" + permissionService.update(permissionVo));
    }

    @RequestMapping("delete")
    public Object delete(String code) {
        log.debug("正在删除菜单:[{}]", code);
        return ResponseUtil.success("操作成功,删除记录条数:" + permissionService.deleteMenu(code));
    }

}
